chai = require 'chai'
chai.should()
sinon = require 'sinon'
should = require 'should'
{Refresh} = require "../src/refresh"
{Token} = require '../src/token'
{RefreshRequest} = require '../src/refreshRequest'
{MemoryRepository} = require '../src/memoryRepository'
{printObject} = require '../src/printObject'
describe 'Refresh instance', ->
  memoryRepository = new MemoryRepository()
  refresh = new Refresh(memoryRepository, memoryRepository, null)

  validateApiKeySpy = sinon.spy(refresh, 'validateApiKey')
  createTokenSpy = sinon.spy(refresh, 'createAndStoreAccessToken')
  token = new Token()
  token.Id = 'tokenId'
  token.Expiration = 'tokenExpiration'
  refreshRequest = new RefreshRequest()
  refreshRequest.ApiKey = "myApiKey"
  refreshRequest.RefreshToken = "myTokenId"

  it 'should call validateToken', (done) ->
    validateTokenSpy = sinon.spy(refresh, 'validateToken')
    apiKey = new Object()
    apiKey.Id = refreshRequest.ApiKey
    memoryRepository.set apiKey.Id, apiKey, ()->
      refresh.refresh refreshRequest, (err, result) ->
        should.not.exist err
        validateTokenSpy.called.should.be.true
        done()

  it 'should call validateApiKey', (done) ->
    refresh.refresh refreshRequest, (err, result) ->
      should.not.exist err
      validateApiKeySpy.called.should.be.true
      done()

  it 'should call createAndStoreAccessToken', (done) ->
    refresh.refresh refreshRequest, (err, result) ->
      should.not.exist err
      createTokenSpy.called.should.be.true
      done()

  it 'should return AccessToken and AccessTokenExpiration',(done) ->
    refresh.refresh refreshRequest, (err, result) ->
      should.not.exist err
      result.AccessToken.should.exist
      result.AccessTokenExpiration.should.exist
      memoryRepository.get result.AccessToken, (err, document) ->
        should.not.exist err
        document.should.exist
        document.Expiration.should.equal result.AccessTokenExpiration
        done()